<template>
  <div class="create-budget">
    <div class="header">
      <h1>新增记账</h1>
      <p class="subtitle">为你的旅行计划创建预算并开始记录</p>
    </div>

    <el-card class="form-card" shadow="never">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="budget-form">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="例如：成都三日游预算" />
        </el-form-item>

        <el-form-item label="总预算" prop="amount">
          <el-input-number v-model="form.amount" :min="0" :step="100" controls-position="right" class="amount-input" />
        </el-form-item>

        <el-form-item label="关联计划" prop="travelPlanId">
          <el-select v-model="form.travelPlanId" placeholder="选择关联的旅行计划">
            <el-option v-for="p in travelPlans" :key="p.id" :label="p.title" :value="p.id" />
          </el-select>
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" class="action-button" @click="onSubmit">保存</el-button>
          <el-button class="action-button" @click="onReset">重置</el-button>
          <el-button class="action-button" @click="goBack">返回</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { createBudget } from '../../api/budget'
import { getTravelPlans } from '../../api/travelPlan'
import { authUtils } from '../../utils/auth'

const router = useRouter()
const formRef = ref()

// 表单模型
const form = reactive({
  title: '',
  amount: 0,
  travelPlanId: null,
})

// 校验规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入总预算', trigger: 'blur' }],
  travelPlanId: [{ required: true, message: '请选择关联计划', trigger: 'change' }],
}

// 旅行计划列表
const travelPlans = ref([])
async function loadTravelPlans() {
  try {
    const currentUserId = authUtils.getCurrentUser()?.id
    const list = await getTravelPlans(currentUserId ? { userId: currentUserId } : {})
    travelPlans.value = list
  } catch (e) {
    console.error('加载旅行计划失败:', e)
    travelPlans.value = []
  }
}

const onSubmit = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return
    const payload = { title: form.title, amount: form.amount, travelPlanId: form.travelPlanId }
    try {
      const res = await createBudget(payload)
      const created = res.data
      // 跳转到详情或列表
      if (created?.id) {
        router.replace(`/budget/${created.id}`)
      } else {
        router.replace('/budget')
      }
    } catch (e) {
      console.error('创建预算失败:', e)
    }
  })
}

const onReset = () => formRef.value?.resetFields()
const goBack = () => router.back()

onMounted(() => {
  loadTravelPlans()
})
</script>

<style scoped>
.create-budget {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
}

.subtitle {
  color: #909399;
}

.form-card {
  border: none;
}

.budget-form {
  padding: 20px;
}

.amount-input {
  width: 220px;
}

.form-actions {
  text-align: center;
  margin-top: 16px;
}

.action-button {
  margin: 0 6px;
}
</style>